import { ts } from 'qvog-dsl';
import {
  native,
  HomeCheckHint,
} from 'qvog-dsl';

const SEVERITY = 2;
const DOC_PATH = 'docs/no-unsafe-mac.md';
const DESCRIPTION = 'Avoid using weak hash algorithms like SHA1 or MD5 in MAC creation. These algorithms are considered insecure and can lead to message integrity compromise.';

const unsafeAlgorithms = ['sha1', 'md5'];

export default native<HomeCheckHint>()()
  .match((node): node is ts.CallExpression => {
    return ts.isCallExpression(node);
  })
  .when((node: ts.CallExpression) => {
    //cryptoFramework.createMac(...)
    if (!ts.isPropertyAccessExpression(node.expression)) { return false };

    const expr = node.expression;
    const callerText = expr.expression.getText();
    const methodName = expr.name.getText();
    const isMacCreation = callerText === 'cryptoFramework' && methodName === 'createMac';
    if (!isMacCreation) { return false };

    const [firstArg] = node.arguments;
    if (!firstArg || !ts.isStringLiteral(firstArg)) { return false };

    const algo = firstArg.text.toLowerCase();
    return unsafeAlgorithms.includes(algo);
  })
  .report({
    severity: SEVERITY,
    description: DESCRIPTION,
    docPath: DOC_PATH,
  });
